package org.ytor.core.sysapi.role.logic;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.ytor.common.util.Colls;
import org.ytor.common.util.Strs;
import org.ytor.common.util.tree.Trees;
import org.ytor.core.sqlflow.BaseLogic;
import org.ytor.core.sysapi.permission.repository.SysRolePermissionRepository;
import org.ytor.core.sysapi.permission.model.SysPermission;
import org.ytor.core.sysapi.role.model.SysRolePermission;
import org.ytor.core.sysapi.role.req.SysRolePermissionReq;
import org.ytor.core.sysapi.role.resp.SysRolePermissionResp;
import org.ytor.core.sysapi.role.model.SysRole;
import org.ytor.core.sysapi.role.repository.SysRoleRepository;

import java.util.ArrayList;
import java.util.List;

/**
 * created by   on 2025年4月13日 16:01:41
 * <br/>
 * SysRole逻辑层
 * <br/>
 */
@Service
@RequiredArgsConstructor
public class SysRoleLogic extends BaseLogic<SysRole, SysRoleRepository> {

    private final SysRolePermissionRepository rolePermissionRepository;

    public List<SysPermission> listAllPermission(String roleId) {
        return repository.listAllPermissionByRoleId(roleId);
    }

    public List<SysRolePermissionResp> listRolePermissions(String roleId) {
        List<SysRolePermission> list = repository.listRolePermissions(roleId);
        List<SysRolePermissionResp> respList = list.stream().map(SysRolePermission::toResp).toList();
        //转为tree
        return Trees.toTree(respList);
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateRolePermissions(SysRolePermissionReq rolePermissionReq) {
        if (Strs.isEmpty(rolePermissionReq.getRoleId())) {
            return;
        }

        //删除权限
        if (Colls.isNotEmpty(rolePermissionReq.getDeletedPermissionIds())) {
            rolePermissionRepository.delete(w -> w.eq(SysRolePermission::getRoleId, rolePermissionReq.getRoleId()).in(SysRolePermission::getPermissionId, rolePermissionReq.getDeletedPermissionIds()));
        }

        //新增权限
        if (Colls.isNotEmpty(rolePermissionReq.getInsertedPermissionIds())) {
            List<SysRolePermission> inserted = new ArrayList<>();
            for (String id : rolePermissionReq.getInsertedPermissionIds()) {
                SysRolePermission rolePermission = new SysRolePermission();
                rolePermission.setRoleId(rolePermissionReq.getRoleId());
                rolePermission.setPermissionId(id);
                inserted.add(rolePermission);
            }
            rolePermissionRepository.insertBatch(inserted);
        }
    }
}